package br.ufrj.neg.artigo.servlet;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.velocity.tools.view.VelocityViewServlet;

import br.ufrj.neg.artigo.bean.ArtigoBean;
import br.ufrj.neg.artigo.model.ArtigoModel;
import br.ufrj.neg.bean.Idioma;
import br.ufrj.neg.constants.General;


public class DownloadArtigo extends VelocityViewServlet {

	private static final long serialVersionUID = 1L;

	// private static Logger log = Logger.getLogger("rootLogger");

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
		try {
			HttpSession session = request.getSession(false);
			
			String idArtigoDownload = request.getParameter("idArtigoDownload");
			ArtigoModel aM = new ArtigoModel();
			Idioma idioma = (Idioma) request.getAttribute("idioma");
			ArtigoBean aB = new ArtigoBean(idioma);
			aB.setId(Integer.parseInt(idArtigoDownload));		
			aB = aM.getArtigo(aB);

			//response.setContentType("application/pdf");
			
			
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition","attachment; filename="+ aB.getNome() + ".pdf");
						
//			response.setHeader("Content-Disposition", "attachment;filename="+ aB.getNome());

			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentLength(aB.getArtigoAsByte().length);
			outputStream.write(aB.getArtigoAsByte());
			outputStream.flush();
			outputStream.close();

		} catch (Exception e) {
			System.out.println(e);
			request.getRequestDispatcher(General.TELA_ERRO_500).forward(request,
					response);
		}
	}

}
